package android.demo.handler;

import android.demo.BaseActivity;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

public class HandlerActivityD extends BaseActivity {

	private TextView tv;
	private UIUpdateThread myUpdateThread = new UIUpdateThread(); //定义一个自己的UI更新的线程类
	private MyHandler mHandler = new MyHandler(); //定义自己的一个Handler类
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Button btn = new Button(this);
		btn.setText("开始");
		btn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Log.i(TAG, "主线程运行ID：" + Thread.currentThread().getId());
				new Thread(myUpdateThread).start();//起一个自己定义的线程
				
			}
		});
		LayoutParams btnParams = new LayoutParams(100, 100);
		addContentView(btn, btnParams);
		
		tv = new TextView(this);
		tv.setBackgroundColor(Color.WHITE);
		LayoutParams tvParams = new LayoutParams(200, 200);
		tvParams.setMargins(350, 350, 10, 10);
		addContentView(tv, tvParams);
	}
	
	
	private class MyHandler extends Handler { //继承Handler类时，必须重写handleMessage方法 
		@Override
		public void handleMessage(Message msg) { //执行接收到的通知，此时执行的顺序是按照队列进行，即先进先出 
			tv.setText(msg.toString());
			Log.i(TAG, "Current Handler Thread ID:" + Thread.currentThread().getId());
		}
	}

	//该线程将会在单独的线程中运行
	private class UIUpdateThread implements Runnable {  
		int i = 1;
	    public void run() {  
	        while (i < 5) {  
	            Message msg = mHandler.obtainMessage();
	            mHandler.sendMessage(msg);
	            Log.i(TAG, "新线程运行ID：" + Thread.currentThread().getId());
				i++;
	            try {  
	                Thread.sleep(4000);  
	            } catch (InterruptedException e) {  
	                e.printStackTrace();  
	            }  
	        }  
	    }  
	}
}

		



